import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/collect.dart';
import '../models/category.dart';
import '../services/api_service.dart';
import '../theme/theme_manager.dart';
import '../theme/app_theme.dart';
import 'collection_detail_page.dart';

// 卡片样式枚举
enum CardStyle {
  gradient('渐变卡片'),
  simple('简约卡片'),
  shadow('投影卡片'),
  border('边框卡片'),
  minimal('极简卡片');

  final String name;
  const CardStyle(this.name);
}

class HomePage extends StatefulWidget {
  final VoidCallback? onRefresh;

  const HomePage({super.key, this.onRefresh});

  @override
  State<HomePage> createState() => HomePageState();
}

// 将类名改为public，方便外部访问
class HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  List<CollectionItem> _collections = [];
  List<CollectionItem> _favoriteCollections = [];
  List<Category> _categories = [];
  bool _isLoading = true;
  bool _isFavoriteLoading = true;
  bool _isCategoriesLoading = false;
  String? _errorMessage;
  String? _favoriteErrorMessage;
  String? _selectedCategoryId;
  String _selectedCategoryName = '懒熊收藏';
  CardStyle _cardStyle = CardStyle.gradient;
  static const String _cardStyleKey = 'card_style';
  static const String _collectionsKey = 'cached_collections';
  static const String _favoritesKey = 'cached_favorites';

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(_onTabChanged);
    _loadCachedData(); // 先加载缓存数据
    loadCollections();
    loadFavoriteCollections();
    loadCategories();
    _loadCardStyle();
  }

  @override
  void dispose() {
    _tabController.removeListener(_onTabChanged);
    _tabController.dispose();
    super.dispose();
  }

  void _onTabChanged() {
    if (!_tabController.indexIsChanging) {
      // 只在tab切换完成时刷新，避免在滑动过程中频繁刷新
      if (_tabController.index == 0) {
        // 切换到"我的"tab，刷新普通收藏列表（静默刷新，不显示加载框）
        loadCollections(showLoading: false);
      } else if (_tabController.index == 1) {
        // 切换到"喜欢"tab，刷新喜欢列表（静默刷新，不显示加载框）
        loadFavoriteCollections(showLoading: false);
      }
    }
  }

  /// 加载缓存数据
  Future<void> _loadCachedData() async {
    try {
      final prefs = await SharedPreferences.getInstance();

      // 加载收藏列表缓存
      final cachedCollections = prefs.getString(_collectionsKey);
      if (cachedCollections != null) {
        final List<dynamic> jsonList = json.decode(cachedCollections);
        setState(() {
          _collections = jsonList.map((json) => CollectionItem.fromJson(json)).toList();
          _isLoading = false;
        });
      }

      // 加载喜欢列表缓存
      final cachedFavorites = prefs.getString(_favoritesKey);
      if (cachedFavorites != null) {
        final List<dynamic> jsonList = json.decode(cachedFavorites);
        setState(() {
          _favoriteCollections = jsonList.map((json) => CollectionItem.fromJson(json)).toList();
          _isFavoriteLoading = false;
        });
      }
    } catch (e) {
      print('加载缓存数据失败: $e');
    }
  }

  /// 保存收藏列表到缓存
  Future<void> _saveCachedCollections(List<CollectionItem> collections) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final jsonList = collections.map((item) => item.toJson()).toList();
      await prefs.setString(_collectionsKey, json.encode(jsonList));
    } catch (e) {
      print('保存收藏列表缓存失败: $e');
    }
  }

  /// 保存喜欢列表到缓存
  Future<void> _saveCachedFavorites(List<CollectionItem> favorites) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final jsonList = favorites.map((item) => item.toJson()).toList();
      await prefs.setString(_favoritesKey, json.encode(jsonList));
    } catch (e) {
      print('保存喜欢列表缓存失败: $e');
    }
  }

  Future<void> _loadCardStyle() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final styleIndex = prefs.getInt(_cardStyleKey);
      if (styleIndex != null && styleIndex < CardStyle.values.length) {
        setState(() {
          _cardStyle = CardStyle.values[styleIndex];
        });
      }
    } catch (e) {
      print('加载卡片样式失败: $e');
    }
  }

  Future<void> _saveCardStyle(CardStyle style) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setInt(_cardStyleKey, style.index);
    } catch (e) {
      print('保存卡片样式失败: $e');
    }
  }

  Future<void> loadCategories() async {
    setState(() {
      _isCategoriesLoading = true;
    });

    try {
      final categories = await ApiService.getCategoryList();
      setState(() {
        _categories = categories;
        _isCategoriesLoading = false;
      });
    } catch (e) {
      setState(() {
        _isCategoriesLoading = false;
      });
      print('加载分类失败: $e');
    }
  }

  Future<void> loadCollections({bool showLoading = true}) async {
    if (showLoading) {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });
    }

    try {
      final collections = await ApiService.getCollectionList(
        categoryId: _selectedCategoryId,
      );
      setState(() {
        _collections = collections;
        if (showLoading) {
          _isLoading = false;
        }
      });
      // 保存到缓存
      _saveCachedCollections(collections);
    } catch (e) {
      setState(() {
        if (showLoading) {
          _errorMessage = '加载失败: $e';
          _isLoading = false;
        }
      });
      print('加载收藏列表失败: $e');
    }
  }

  Future<void> loadFavoriteCollections({bool showLoading = true}) async {
    if (showLoading) {
      setState(() {
        _isFavoriteLoading = true;
        _favoriteErrorMessage = null;
      });
    }

    try {
      final collections = await ApiService.getCollectionList(
        isFavorite: true,
      );
      setState(() {
        _favoriteCollections = collections;
        if (showLoading) {
          _isFavoriteLoading = false;
        }
      });
      // 保存到缓存
      _saveCachedFavorites(collections);
    } catch (e) {
      setState(() {
        if (showLoading) {
          _favoriteErrorMessage = '加载失败: $e';
          _isFavoriteLoading = false;
        }
      });
      print('加载喜欢列表失败: $e');
    }
  }

  void _onCategorySelected(String categoryId, String categoryName) {
    setState(() {
      _selectedCategoryId = categoryId;
      _selectedCategoryName = categoryName;
    });
    loadCollections();
  }

  Future<void> _showAddCategoryDialog(BuildContext context) async {
    final nameController = TextEditingController();

    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('新增分类'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: '分类名称',
            border: OutlineInputBorder(),
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              if (nameController.text.trim().isEmpty) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('请输入分类名称')),
                );
                return;
              }
              Navigator.pop(context, true);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (result == true && nameController.text.trim().isNotEmpty) {
      try {
        // 显示加载提示
        if (context.mounted) {
          showDialog(
            context: context,
            barrierDismissible: false,
            builder: (context) => const Center(
              child: CircularProgressIndicator(),
            ),
          );
        }

        await ApiService.createCategory(
          name: nameController.text.trim(),
          parentId: _selectedCategoryId == '-1' ? null : _selectedCategoryId,
        );

        if (context.mounted) {
          Navigator.pop(context); // 关闭加载对话框
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('创建成功')),
          );
          // 重新加载分类列表
          loadCategories();
        }
      } catch (e) {
        if (context.mounted) {
          Navigator.pop(context); // 关闭加载对话框
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('创建失败: $e')),
          );
        }
      }
    }

    nameController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // macOS 平台使用左右布局
    if (Platform.isMacOS) {
      return _buildMacOSLayout();
    }

    // 其他平台使用原有的抽屉布局
    return Scaffold(
      appBar: AppBar(
        leading: Builder(
          builder: (context) => IconButton(
            icon: const Icon(Icons.menu),
            onPressed: () {
              Scaffold.of(context).openDrawer();
            },
            tooltip: '菜单',
          ),
        ),
        flexibleSpace: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            TabBar(
              controller: _tabController,
              tabs: [
                Tab(
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        _selectedCategoryId == null || _selectedCategoryId == '-1'
                            ? '我的'
                            : _selectedCategoryName,
                        style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                      if (_selectedCategoryId != null && _selectedCategoryId != '-1') ...[
                        const SizedBox(width: 4),
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              _selectedCategoryId = null;
                              _selectedCategoryName = '我的';
                            });
                            loadCollections();
                          },
                          child: const Icon(Icons.close, size: 16),
                        ),
                      ],
                    ],
                  ),
                ),
                const Tab(icon: Icon(Icons.favorite, size: 20)),
              ],
              indicatorColor: Colors.white,
              labelColor: Colors.white,
              unselectedLabelColor: Colors.white70,
              labelStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              unselectedLabelStyle: const TextStyle(fontSize: 16),
              isScrollable: true,
              indicatorSize: TabBarIndicatorSize.label,
              labelPadding: const EdgeInsets.symmetric(horizontal: 8),
              dividerColor: Colors.transparent,
              dividerHeight: 0,
              tabAlignment: TabAlignment.center,
            ),
          ],
        ),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        elevation: 0,
        actions: [
          PopupMenuButton<String>(
            tooltip: '更多',
            onSelected: (value) {
              if (value.startsWith('theme_')) {
                final themeIndex = int.parse(value.split('_')[1]);
                final themeManager = Provider.of<ThemeManager>(context, listen: false);
                themeManager.setTheme(AppThemeType.values[themeIndex]);
              } else if (value.startsWith('card_')) {
                final styleIndex = int.parse(value.split('_')[1]);
                final newStyle = CardStyle.values[styleIndex];
                setState(() {
                  _cardStyle = newStyle;
                });
                _saveCardStyle(newStyle);
              }
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                enabled: false,
                child: Text(
                  '主题配色',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 12,
                  ),
                ),
              ),
              ...AppThemeType.values.asMap().entries.map((entry) {
                final theme = entry.value;
                final themeManager = Provider.of<ThemeManager>(context, listen: false);
                final isSelected = themeManager.currentTheme == theme;
                return PopupMenuItem(
                  value: 'theme_${entry.key}',
                  child: Row(
                    children: [
                      Container(
                        width: 20,
                        height: 20,
                        decoration: BoxDecoration(
                          color: theme.primaryColor,
                          borderRadius: BorderRadius.circular(4),
                          border: Border.all(
                            color: Colors.grey,
                            width: 1,
                          ),
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(child: Text(theme.name)),
                      if (isSelected)
                        Icon(
                          Icons.check,
                          size: 16,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                    ],
                  ),
                );
              }).toList(),
              const PopupMenuDivider(),
              const PopupMenuItem(
                enabled: false,
                child: Text(
                  '卡片样式',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 12,
                  ),
                ),
              ),
              ...CardStyle.values.asMap().entries.map((entry) {
                final style = entry.value;
                final isSelected = _cardStyle == style;
                return PopupMenuItem(
                  value: 'card_${entry.key}',
                  child: Row(
                    children: [
                      SizedBox(
                        width: 20,
                        child: isSelected
                            ? const Icon(Icons.check, size: 16)
                            : null,
                      ),
                      const SizedBox(width: 8),
                      Expanded(child: Text(style.name)),
                    ],
                  ),
                );
              }).toList(),
            ],
          ),
        ],
      ),
      drawer: Drawer(
        child: Column(
          children: [
            DrawerHeader(
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.inversePrimary,
              ),
              child: const SizedBox(
                width: double.infinity,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.collections_bookmark, size: 64),
                    SizedBox(height: 8),
                    Text(
                      '懒熊收藏',
                      style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: _isCategoriesLoading
                  ? const Center(child: CircularProgressIndicator())
                  : RefreshIndicator(
                      onRefresh: loadCategories,
                      child: ListView(
                        padding: EdgeInsets.zero,
                        children: [
                          ListTile(
                            leading: const Icon(Icons.folder_off),
                            title: const Text('未分类'),
                            selected: _selectedCategoryId == '-1',
                            trailing: IconButton(
                              icon: const Icon(Icons.add),
                              onPressed: () {
                                _showAddCategoryDialog(context);
                              },
                              tooltip: '新增分类',
                            ),
                            onTap: () {
                              Navigator.pop(context);
                              _onCategorySelected('-1', '未分类');
                            },
                          ),
                          ..._categories.map((category) => _buildCategoryItem(category)),
                        ],
                      ),
                    ),
            ),
            const Divider(height: 1),
            ListTile(
              leading: const Icon(Icons.settings),
              title: const Text('设置'),
              onTap: () {
                Navigator.pop(context);
                // TODO: 跳转到设置页面
              },
            ),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildBody(_collections, _isLoading, _errorMessage, loadCollections),
          _buildBody(_favoriteCollections, _isFavoriteLoading, _favoriteErrorMessage, loadFavoriteCollections),
        ],
      ),
    );
  }

  // macOS 平台的左右布局
  Widget _buildMacOSLayout() {
    return Scaffold(
      appBar: AppBar(
        title: TabBar(
          controller: _tabController,
          tabs: [
            Tab(
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    _selectedCategoryId == null || _selectedCategoryId == '-1'
                        ? '我的'
                        : _selectedCategoryName,
                    style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  if (_selectedCategoryId != null && _selectedCategoryId != '-1') ...[
                    const SizedBox(width: 4),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          _selectedCategoryId = null;
                          _selectedCategoryName = '我的';
                        });
                        loadCollections();
                      },
                      child: const Icon(Icons.close, size: 16),
                    ),
                  ],
                ],
              ),
            ),
            const Tab(icon: Icon(Icons.favorite, size: 20)),
          ],
          indicatorColor: Colors.white,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white70,
          labelStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          unselectedLabelStyle: const TextStyle(fontSize: 16),
          isScrollable: true,
          indicatorSize: TabBarIndicatorSize.label,
          labelPadding: const EdgeInsets.symmetric(horizontal: 8),
          dividerColor: Colors.transparent,
          dividerHeight: 0,
          tabAlignment: TabAlignment.center,
        ),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        elevation: 0,
        actions: [
          PopupMenuButton<String>(
            tooltip: '更多',
            onSelected: (value) {
              if (value.startsWith('theme_')) {
                final themeIndex = int.parse(value.split('_')[1]);
                final themeManager = Provider.of<ThemeManager>(context, listen: false);
                themeManager.setTheme(AppThemeType.values[themeIndex]);
              } else if (value.startsWith('card_')) {
                final styleIndex = int.parse(value.split('_')[1]);
                final newStyle = CardStyle.values[styleIndex];
                setState(() {
                  _cardStyle = newStyle;
                });
                _saveCardStyle(newStyle);
              }
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                enabled: false,
                child: Text(
                  '主题配色',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 12,
                  ),
                ),
              ),
              ...AppThemeType.values.asMap().entries.map((entry) {
                final theme = entry.value;
                final themeManager = Provider.of<ThemeManager>(context, listen: false);
                final isSelected = themeManager.currentTheme == theme;
                return PopupMenuItem(
                  value: 'theme_${entry.key}',
                  child: Row(
                    children: [
                      Container(
                        width: 20,
                        height: 20,
                        decoration: BoxDecoration(
                          color: theme.primaryColor,
                          borderRadius: BorderRadius.circular(4),
                          border: Border.all(
                            color: Colors.grey,
                            width: 1,
                          ),
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(child: Text(theme.name)),
                      if (isSelected)
                        Icon(
                          Icons.check,
                          size: 16,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                    ],
                  ),
                );
              }).toList(),
              const PopupMenuDivider(),
              const PopupMenuItem(
                enabled: false,
                child: Text(
                  '卡片样式',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 12,
                  ),
                ),
              ),
              ...CardStyle.values.asMap().entries.map((entry) {
                final style = entry.value;
                final isSelected = _cardStyle == style;
                return PopupMenuItem(
                  value: 'card_${entry.key}',
                  child: Row(
                    children: [
                      SizedBox(
                        width: 20,
                        child: isSelected
                            ? const Icon(Icons.check, size: 16)
                            : null,
                      ),
                      const SizedBox(width: 8),
                      Expanded(child: Text(style.name)),
                    ],
                  ),
                );
              }).toList(),
            ],
          ),
        ],
      ),
      body: Row(
        children: [
          // 左侧分类栏
          _buildSidebar(),
          // 右侧收藏列表
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildBody(_collections, _isLoading, _errorMessage, loadCollections),
                _buildBody(_favoriteCollections, _isFavoriteLoading, _favoriteErrorMessage, loadFavoriteCollections),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建侧边栏
  Widget _buildSidebar() {
    return Container(
      width: 250,
      decoration: BoxDecoration(
        color: Theme.of(context).brightness == Brightness.light
            ? Colors.grey[100]
            : Colors.grey[900],
        border: Border(
          right: BorderSide(
            color: Theme.of(context).dividerColor,
            width: 1,
          ),
        ),
      ),
      child: Column(
        children: [
          // 顶部标题
          Container(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                const Icon(Icons.collections_bookmark, size: 32),
                const SizedBox(width: 8),
                const Expanded(
                  child: Text(
                    '懒熊收藏',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.refresh, size: 20),
                  onPressed: _isCategoriesLoading ? null : loadCategories,
                  tooltip: '刷新分类',
                ),
              ],
            ),
          ),
          const Divider(height: 1),
          // 分类列表
          Expanded(
            child: _isCategoriesLoading
                ? const Center(child: CircularProgressIndicator())
                : ListView(
                    padding: EdgeInsets.zero,
                    children: [
                      ListTile(
                        leading: const Icon(Icons.folder_off),
                        title: const Text('未分类'),
                        selected: _selectedCategoryId == '-1',
                        trailing: IconButton(
                          icon: const Icon(Icons.add),
                          onPressed: () {
                            _showAddCategoryDialog(context);
                          },
                          tooltip: '新增分类',
                        ),
                        onTap: () {
                          _onCategorySelected('-1', '未分类');
                        },
                      ),
                      ..._categories.map((category) => _buildCategoryItem(category, isMacOS: true)),
                    ],
                  ),
          ),
          const Divider(height: 1),
          // 底部设置
          ListTile(
            leading: const Icon(Icons.settings),
            title: const Text('设置'),
            onTap: () {
              // TODO: 跳转到设置页面
            },
          ),
        ],
      ),
    );
  }

  Widget _buildCategoryItem(Category category, {int level = 0, bool isMacOS = false}) {
    if (category.children.isEmpty) {
      // 没有子分类，直接显示
      return ListTile(
        leading: Icon(
          Icons.folder,
          size: 24 - (level * 2.0).clamp(0, 8),
        ),
        title: Text(category.name),
        selected: _selectedCategoryId == category.id,
        contentPadding: EdgeInsets.only(
          left: 16 + (level * 16.0),
          right: 16,
        ),
        onTap: () {
          if (!isMacOS) {
            Navigator.pop(context);
          }
          _onCategorySelected(category.id, category.name);
        },
      );
    }

    // 递归检查是否有任何子孙分类被选中
    bool hasSelectedDescendant(Category cat) {
      if (cat.id == _selectedCategoryId) return true;
      for (var child in cat.children) {
        if (hasSelectedDescendant(child)) return true;
      }
      return false;
    }

    final hasSelected = hasSelectedDescendant(category);

    // 有子分类，使用 ExpansionTile，但标题可以点击
    return Theme(
      data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
      child: ExpansionTile(
        leading: Icon(
          Icons.folder,
          size: 24 - (level * 2.0).clamp(0, 8),
        ),
        title: GestureDetector(
          onTap: () {
            if (!isMacOS) {
              Navigator.pop(context);
            }
            _onCategorySelected(category.id, category.name);
          },
          child: Container(
            color: Colors.transparent,
            child: Text(
              category.name,
              style: TextStyle(
                color: _selectedCategoryId == category.id
                    ? Theme.of(context).colorScheme.primary
                    : null,
                fontWeight: _selectedCategoryId == category.id
                    ? FontWeight.bold
                    : FontWeight.normal,
              ),
            ),
          ),
        ),
        initiallyExpanded: hasSelected,
        tilePadding: EdgeInsets.only(
          left: 16 + (level * 16.0),
          right: 16,
        ),
        children: category.children.map((child) {
          // 递归调用，支持多层嵌套
          return _buildCategoryItem(child, level: level + 1, isMacOS: isMacOS);
        }).toList(),
      ),
    );
  }

  Widget _buildBody(
    List<CollectionItem> collections,
    bool isLoading,
    String? errorMessage,
    Future<void> Function() onRefresh,
  ) {
    if (isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.red,
            ),
            const SizedBox(height: 16),
            Text(errorMessage),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: onRefresh,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (collections.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.inbox_outlined,
              size: 64,
              color: Colors.grey,
            ),
            SizedBox(height: 16),
            Text('暂无收藏'),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: onRefresh,
      child: MasonryGridView.count(
        crossAxisCount: Platform.isMacOS ? 4 : 2,
        mainAxisSpacing: 5,
        crossAxisSpacing: 5,
        padding: const EdgeInsets.all(5),
        itemCount: collections.length,
        itemBuilder: (context, index) {
          return _buildCollectionCard(collections[index], collections);
        },
      ),
    );
  }

  Widget _buildCollectionCard(CollectionItem item, List<CollectionItem> collections) {
    switch (_cardStyle) {
      case CardStyle.gradient:
        return _buildGradientCard(item, collections);
      case CardStyle.simple:
        return _buildSimpleCard(item, collections);
      case CardStyle.shadow:
        return _buildShadowCard(item, collections);
      case CardStyle.border:
        return _buildBorderCard(item, collections);
      case CardStyle.minimal:
        return _buildMinimalCard(item, collections);
    }
  }

  // 样式1：简约卡片
  Widget _buildSimpleCard(CollectionItem item, List<CollectionItem> collections) {
    const double minHeight = 150.0;
    const double maxHeight = 450.0;
    const double padding = 12.0;

    return GestureDetector(
      onTap: () {
        final index = collections.indexOf(item);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => CollectionDetailPage(
              items: collections,
              initialIndex: index,
            ),
          ),
        );
      },
      child: Card(
        elevation: 0,
        margin: EdgeInsets.zero,
        color: Theme.of(context).brightness == Brightness.light
            ? Colors.grey[200]
            : Colors.grey[800],
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(3),
        ),
        child: ConstrainedBox(
          constraints: const BoxConstraints(
            minHeight: minHeight,
            maxHeight: maxHeight,
          ),
          child: IntrinsicHeight(
            child: Container(
              padding: const EdgeInsets.all(padding),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  if (item.title.isNotEmpty) ...[
                    Text(
                      item.title,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.center,
                    ),
                    if (item.content.isNotEmpty) const SizedBox(height: 8),
                  ],
                  if (item.content.isNotEmpty) ...[
                    Flexible(
                      child: Text(
                        item.content,
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[700],
                        ),
                        maxLines: 8,
                        overflow: TextOverflow.ellipsis,
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ],
                  if (item.source.isNotEmpty) ...[
                    const SizedBox(height: 8),
                    Text(
                      '—— ${item.source}',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                        fontStyle: FontStyle.italic,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.center,
                    ),
                  ],
                  if (item.categoryName.isNotEmpty) ...[
                    const SizedBox(height: 8),
                    GestureDetector(
                      onTap: () {
                        _onCategorySelected(item.categoryId, item.categoryName);
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.blue[100],
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          item.categoryName,
                          style: TextStyle(
                            fontSize: 11,
                            color: Colors.blue[800],
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 样式2：投影卡片
  Widget _buildShadowCard(CollectionItem item, List<CollectionItem> collections) {
    const double minHeight = 150.0;
    const double maxHeight = 450.0;

    return GestureDetector(
      onTap: () {
        final index = collections.indexOf(item);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => CollectionDetailPage(
              items: collections,
              initialIndex: index,
            ),
          ),
        );
      },
      child: Container(
        constraints: const BoxConstraints(
          minHeight: minHeight,
          maxHeight: maxHeight,
        ),
        decoration: BoxDecoration(
          color: Theme.of(context).brightness == Brightness.light
              ? Colors.white
              : Colors.grey[850],
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.08),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            if (item.title.isNotEmpty) ...[
              Text(
                item.title,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
              ),
              if (item.content.isNotEmpty) const SizedBox(height: 8),
            ],
            if (item.content.isNotEmpty) ...[
              Flexible(
                child: Text(
                  item.content,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[700],
                  ),
                  maxLines: 8,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.center,
                ),
              ),
            ],
            if (item.source.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text(
                '—— ${item.source}',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                  fontStyle: FontStyle.italic,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
              ),
            ],
            if (item.categoryName.isNotEmpty) ...[
              const SizedBox(height: 8),
              GestureDetector(
                onTap: () {
                  _onCategorySelected(item.categoryId, item.categoryName);
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 4,
                  ),
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primaryContainer,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    item.categoryName,
                    style: TextStyle(
                      fontSize: 11,
                      color: Theme.of(context).colorScheme.onPrimaryContainer,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  // 样式3：渐变卡片
  Widget _buildGradientCard(CollectionItem item, List<CollectionItem> collections) {
    const double minHeight = 150.0;
    const double maxHeight = 450.0;

    return GestureDetector(
      onTap: () {
        final index = collections.indexOf(item);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => CollectionDetailPage(
              items: collections,
              initialIndex: index,
            ),
          ),
        );
      },
      child: Container(
        constraints: const BoxConstraints(
          minHeight: minHeight,
          maxHeight: maxHeight,
        ),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Theme.of(context).colorScheme.primary.withOpacity(0.15),
              Theme.of(context).colorScheme.secondary.withOpacity(0.15),
            ],
          ),
          borderRadius: BorderRadius.circular(16),
        ),
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            if (item.title.isNotEmpty) ...[
              Text(
                item.title,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
              ),
              if (item.content.isNotEmpty) const SizedBox(height: 8),
            ],
            if (item.content.isNotEmpty) ...[
              Flexible(
                child: Text(
                  item.content,
                  style: TextStyle(
                    fontSize: 14,
                    color: Theme.of(context).brightness == Brightness.light
                        ? Colors.black87
                        : Colors.white.withOpacity(0.87),
                  ),
                  maxLines: 8,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.center,
                ),
              ),
            ],
            if (item.source.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text(
                '—— ${item.source}',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                  fontStyle: FontStyle.italic,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
              ),
            ],
            if (item.categoryName.isNotEmpty) ...[
              const SizedBox(height: 8),
              GestureDetector(
                onTap: () {
                  _onCategorySelected(item.categoryId, item.categoryName);
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 4,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.9),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    item.categoryName,
                    style: TextStyle(
                      fontSize: 11,
                      color: Theme.of(context).colorScheme.primary,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  // 样式4：边框卡片
  Widget _buildBorderCard(CollectionItem item, List<CollectionItem> collections) {
    const double minHeight = 150.0;
    const double maxHeight = 450.0;

    return GestureDetector(
      onTap: () {
        final index = collections.indexOf(item);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => CollectionDetailPage(
              items: collections,
              initialIndex: index,
            ),
          ),
        );
      },
      child: Container(
        constraints: const BoxConstraints(
          minHeight: minHeight,
          maxHeight: maxHeight,
        ),
        decoration: BoxDecoration(
          color: Colors.transparent,
          border: Border.all(
            color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
            width: 2,
          ),
          borderRadius: BorderRadius.circular(8),
        ),
        padding: const EdgeInsets.all(14),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            if (item.title.isNotEmpty) ...[
              Text(
                item.title,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
              ),
              if (item.content.isNotEmpty) const SizedBox(height: 8),
            ],
            if (item.content.isNotEmpty) ...[
              Flexible(
                child: Text(
                  item.content,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[700],
                  ),
                  maxLines: 8,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.center,
                ),
              ),
            ],
            if (item.source.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text(
                '—— ${item.source}',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                  fontStyle: FontStyle.italic,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
              ),
            ],
            if (item.categoryName.isNotEmpty) ...[
              const SizedBox(height: 8),
              GestureDetector(
                onTap: () {
                  _onCategorySelected(item.categoryId, item.categoryName);
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 4,
                  ),
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primaryContainer,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    item.categoryName,
                    style: TextStyle(
                      fontSize: 11,
                      color: Theme.of(context).colorScheme.onPrimaryContainer,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  // 样式5：极简卡片
  Widget _buildMinimalCard(CollectionItem item, List<CollectionItem> collections) {
    const double minHeight = 150.0;
    const double maxHeight = 450.0;

    return GestureDetector(
      onTap: () {
        final index = collections.indexOf(item);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => CollectionDetailPage(
              items: collections,
              initialIndex: index,
            ),
          ),
        );
      },
      child: Container(
        constraints: const BoxConstraints(
          minHeight: minHeight,
          maxHeight: maxHeight,
        ),
        decoration: BoxDecoration(
          color: Theme.of(context).brightness == Brightness.light
              ? Colors.white
              : Colors.grey[900],
          borderRadius: BorderRadius.circular(4),
        ),
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            if (item.title.isNotEmpty) ...[
              Text(
                item.title,
                style: const TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
              ),
              if (item.content.isNotEmpty) const SizedBox(height: 10),
            ],
            if (item.content.isNotEmpty) ...[
              Flexible(
                child: Text(
                  item.content,
                  style: TextStyle(
                    fontSize: 13,
                    color: Colors.grey[600],
                    height: 1.5,
                  ),
                  maxLines: 8,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.center,
                ),
              ),
            ],
            if (item.source.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text(
                item.source,
                style: TextStyle(
                  fontSize: 11,
                  color: Colors.grey[500],
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
              ),
            ],
            if (item.categoryName.isNotEmpty) ...[
              const SizedBox(height: 8),
              GestureDetector(
                onTap: () {
                  _onCategorySelected(item.categoryId, item.categoryName);
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 3,
                  ),
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
                      width: 1,
                    ),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Text(
                    item.categoryName,
                    style: TextStyle(
                      fontSize: 10,
                      color: Theme.of(context).colorScheme.primary,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
